# coding : utf-8

import automationframework
# from automationframework.automationserver import data_read  # 单独此文件需要开启 windows
from . import data_read, automation_operate_function  # 启动django服务需要开启
from appium import webdriver


class RunAppAutomation:
    def __init__(self):
        self.wait_sleep_time, self.wait_element_time, self.webview_wait_time = 3, 6, 2  # 休眠时间 # 等待元素休眠时间
        self.check_device_packages = lambda deivce_name, packages_name: True if automationframework.os.popen(
            'adb -s %s shell pm list packages | grep \'%s\'' % (deivce_name, packages_name)).read() else False  # 检查设备是否有包名
        self.check_system = lambda: True if automationframework.os.name == 'nt' else False  # 检查当前系统 nt是Windows posix或其他是非Windows
        self.get_device_android_version = lambda device_id: automationframework.os.popen(
            'adb -s %s shell getprop ro.build.version.release' % device_id).read().strip()  # 获取手机安卓系统版本

    # 获取webview_path路径
    def get_webview_path(self, device_id):
        device_chrome_driver_name = RunAppAutomation().get_device_chrome_driver_version(device_id)
        chrome_file_name = RunAppAutomation().get_chrome_driver_version(device_chrome_driver_name)
        if chrome_file_name:
            chrome_driver_file_path = RunAppAutomation().create_chrome_driver_path(device_id, chrome_file_name)
            if chrome_file_name == 'chromedriver':
                print('当前设备没有找到对应的chromedriver版本, 使用默认的chromedriver, 如果在切换webview时报错, 请及时更换webview, 设备id: %s' % (device_id))
            print('当前chrome_driver_file_path路径: %s' % (chrome_driver_file_path))
            return chrome_driver_file_path
        else:
            return False

    # 创建chromedriver路径
    def create_chrome_driver_path(self, device_id, chrome_file_name):
        current_path = automationframework.os.getcwd() + '/static/chromedriver'
        chrome_driver_file_path = current_path + '/%s' % (device_id)
        if automationframework.os.path.exists(chrome_driver_file_path) is False:
            automationframework.os.mkdir(current_path + '/%s' % device_id)  # 创建文件夹
        if 'chrome' not in str(automationframework.os.listdir(chrome_driver_file_path)):  # 检查这个路径下有没有chromedriver文件 如果没有则去创建
            if chrome_file_name and automationframework.os.path.exists(current_path + '/%s' % (chrome_file_name)):
                automationframework.shutil.copy(current_path + '/%s' % (chrome_file_name), chrome_driver_file_path + '/%s' % (chrome_file_name))
            else:
                automationframework.shutil.copy(current_path + '/chromedriver', chrome_driver_file_path + '/chromedriver')
        return chrome_driver_file_path

    # chromedriver版本对照
    def get_chrome_driver_version(self, device_version_names, ):
        chrome_drivers = {
            'chromedriverv55-57': ['56'],
            'chromedriverv63-65': ['64'],
            'chromedriver': 'default'
        }
        if device_version_names != 'default':
            chrome_file_name = 'chromedriver'  # 默认是default 如果找不到对应chromedriverv则取默认的
            for chrome_drivers_key, chrome_drivers_value in chrome_drivers.items():
                for x in chrome_drivers_value:
                    if x in device_version_names:
                        chrome_file_name = chrome_drivers_key
                        break
            return chrome_file_name
        else:
            return False

    # 获取当前系统chromedriver版本
    def get_device_chrome_driver_version(self, device_id):
        if self.check_system():
            device_chrome_driver_name = automationframework.os.popen('adb -s %s shell dumpsys package com.google.android.webview | find "versionName"' % (device_id)).read()

        else:
            device_chrome_driver_name = automationframework.os.popen('adb -s %s shell dumpsys package com.google.android.webview | grep "versionName"' % (device_id)).read()
        if 'version' in device_chrome_driver_name:
            device_chrome_driver_name = device_chrome_driver_name.strip().split('=')[1]
        else:
            device_chrome_driver_name = 'default'
        return device_chrome_driver_name

    # 获取安卓设备默认输入法
    def gain_input_method(self, devices_list):
        input_method_list = list(
            map(lambda devices: automationframework.os.popen("adb -s %s shell settings get secure default_input_method" % devices).read().strip('\n'), devices_list))
        return input_method_list

    # 初始化所有安卓设备输入法
    def reset_devices_input_method(self, default_input_method_list, devices_list):
        for m, n in enumerate(devices_list):  # 删除添加的run_appium项目
            if n == 'run_appium':
                devices_list.pop(m)
        for devices_index, devices in enumerate(devices_list):
            automationframework.os.popen('adb -s %s shell ime set %s' % (devices_list[devices_index], default_input_method_list[devices_index]))

    # 获取本地设备信息
    def get_device(self, devices_id):
        device_id_set = set(map(lambda x: x.split('\t')[0] if 'device' in x and 'attached' not in x else '', automationframework.os.popen('adb devices')))  # 获取设备ID, 存放在set集合中
        if '' in device_id_set:
            device_id_set.remove('')
        devices_list = list(device_id_set)  # 存放设备列表

        if devices_id == 'all' or devices_id == '' or devices_id == ' ':
            device_count = len(devices_list)  # 获取的设备数
        elif ',' in devices_id:
            give_devices_set = set(str(devices_id).split(','))
            devices_list = list(device_id_set & give_devices_set)  # 传递过来的deviceid 和本地获取到deviceid做对比 取交集
            device_count = len(devices_list)
        else:
            device_count = 1
            devices_list = [devices_id]
        appium_port, appium_bootstrap_port = RunAppAutomation.create_appium_port(self, device_count)  # 创建appium端口号
        return device_count, devices_list, appium_port, appium_bootstrap_port

    # 清空app数据
    def clear_app_data(self, deivce_name, packages_name):
        try:
            clear_data_result = automationframework.os.popen('adb -s %s shell pm clear \'%s\'' % (deivce_name, packages_name)).read()
            if 'Success' in clear_data_result:
                return True
            else:
                return False
        except Exception as error_result:
            print('代码执行错误,错误内容为: |', error_result, '| 遇到错误的方法名: clear_app_data()')
            return False

    # 删除app
    def uninstall_app_data(self, deivce_name, packages_name):
        try:
            uninstall_app_result = automationframework.os.popen('adb -s %s uninstall %s' % (deivce_name, packages_name)).read()
            if 'Success' in uninstall_app_result:
                return True
            else:
                return False
        except Exception as error_result:
            print('代码执行错误,错误内容为: |', error_result, '| 遇到错误的方法名: uninstall_app_data()')
            return False

    # 检查端口号是否存在
    def check_appium_port(self, appium_port, appium_bootstrap_port):
        if self.check_system():
            if automationframework.os.popen("netstat -ano | findstr %s" % appium_port).read() == '' and automationframework.os.popen(
                    "netstat -ano | findstr %s" % appium_bootstrap_port).read() == '':
                return True
            else:
                return False
        else:
            if automationframework.os.popen("lsof -i tcp:%s" % appium_port).read() == '' and automationframework.os.popen(
                    "lsof -i tcp:%s" % appium_bootstrap_port).read() == '':
                return True
            else:
                return False

    # 创建 appium 端口号
    def create_appium_port(self, device_count):
        count = 0
        appium_port = []  # 存放生成appium的端口号
        appium_bootstrap_port = []  # 存放生成appium bootstrap的端口号
        while count < device_count:
            random_port_number = automationframework.random.randrange(4000, 10000, 2)
            random_bootstrap_number = automationframework.random.randrange(4001, 9999, 2)
            check_appium_port_status = RunAppAutomation().check_appium_port(random_port_number, random_bootstrap_number)
            if random_port_number not in appium_port and random_bootstrap_number not in appium_bootstrap_port and check_appium_port_status == True:
                appium_port.append(random_port_number)  # 获取1000 到 100000之间的偶数
                appium_bootstrap_port.append(random_bootstrap_number)  # 获取1001 到 9999之间的奇数
                count += 1
        return appium_port, appium_bootstrap_port

    # 启动 appium 多线程类
    class LaunchAppiumThread(automationframework.threading.Thread):
        def __init__(self, appium_port, appium_bootstrap_port):
            automationframework.threading.Thread.__init__(self)
            self.appium_port = appium_port  # appium 端口号
            self.appium_bootstrap_port = appium_bootstrap_port  # appium bootstrap 端口号
            self.current_time = automationframework.time.strftime("%Y-%m-%d %H:%M:%S", automationframework.time.localtime(automationframework.time.time()))  # 获取当前时间
            self.log_time_format = automationframework.time.strftime("%Y_%m_%d_%H:%M:%S", automationframework.time.localtime(automationframework.time.time()))  # 获取当前时间

        def run(self):
            # Django 服务开启
            print('启动appium服务,端口号为: %s, 启动时间为: %s' % (self.appium_port, self.current_time))
            appium_cmd = automationframework.subprocess.Popen(
                'appium -p %s -bp %s >static/appiumlog/log_%s_%s_%s.log' % (
                    self.appium_port, self.appium_bootstrap_port, self.appium_port, self.appium_bootstrap_port, self.log_time_format), shell=True)

            # 调试开启
            # appium_cmd = subprocess.Popen('appium -p %s -bp %s' % (self.appium_port, self.appium_bootstrap_port),
            #                               shell=True)
            appium_pid = appium_cmd.pid
            if appium_pid > 0:
                self.current_time = automationframework.time.strftime("%Y-%m-%d %H:%M:%S", automationframework.time.localtime(automationframework.time.time()))
                mysql_cursor, connect_mysql = data_read.DataRead.save_database()
                execute_sql = "insert into `automationquery_automation_appium_pid` (`appium_port`,`appium_bootstrap_port`,`appium_pid`,`created_time`)VALUES('%s','%s','%s','%s')" % (
                    self.appium_port, self.appium_bootstrap_port, appium_pid, self.current_time)
                mysql_cursor.execute(execute_sql)
                connect_mysql.commit()  # 提交数据
                connect_mysql.close()  # 关闭数据库连接
            appium_cmd.wait()

    # 启动appium
    def launch_appium(self, device_count, appium_port, appium_bootstrap_port):
        thread_count = 0
        thread_list = []
        while thread_count < device_count:
            # 创建 appium 多线程 启动appium
            launch_appium_thread = RunAppAutomation.LaunchAppiumThread(appium_port[thread_count],
                                                                       appium_bootstrap_port[thread_count])
            thread_list.append(launch_appium_thread)
            thread_count += 1
        for i in thread_list:
            i.start()
        for y in thread_list:
            y.join()

    # 关闭appium 服务
    def stop_appium(self, device_id, appium_port, contrast_time_stamp):
        format_contrast_time_stamp = automationframework.time.strftime("%Y-%m-%d %H:%M:%S",
                                                                       automationframework.time.localtime(contrast_time_stamp - 60))  # 把contrast_time_stamp - 60 转化为时间格式
        # 获取数据库中所有的appium 服务对应的pid
        mysql_cursor, connect_mysql = data_read.DataRead.save_database()
        execute_sql = "UPDATE `automationquery_automation_appium_pid` SET `devices_id` = '%s' WHERE `appium_port` = '%s'" % (
            device_id, appium_port)
        mysql_cursor.execute(execute_sql)
        connect_mysql.commit()  # 提交数据
        execute_select_sql = "SELECT `appium_pid` FROM `automationquery_automation_appium_pid` WHERE `appium_port` = '%s' AND `created_time` > '%s'" % (
            appium_port, format_contrast_time_stamp)
        mysql_cursor.execute(execute_select_sql)  # 查询数据
        execute_select_sql_results = mysql_cursor.fetchall()  # 返回所有的查询结果数据
        for pid_tuple in execute_select_sql_results:
            appium_pid = pid_tuple[0]
        connect_mysql.close()

        # 关闭appium服务
        if self.check_system():
            appium_pid_list = []
            for get_appium_pid in automationframework.os.popen("netstat -ano | findstr %s" % appium_port):
                if 'LISTENING' in get_appium_pid and str(appium_port) in get_appium_pid:
                    appium_pid_list.append(
                        get_appium_pid.replace(" ", "").strip().split('LISTENING')[1])  # Windows 获取pid
            for kill_pid in appium_pid_list:
                automationframework.os.popen('taskkill -pid %s -t -f ' % kill_pid)  # 关闭appium服务
        else:
            appium_pid_list = []
            for get_appium_pid in automationframework.os.popen("lsof -i tcp:%s" % appium_port):
                if 'LISTEN' in get_appium_pid and str(appium_port) in get_appium_pid:
                    appium_pid_list.append(
                        get_appium_pid.replace(' ', '').strip().split('node')[1].split(automationframework.getpass.getuser())[
                            0])  # linux Unix 获取pid automationframework.getpass.getuser() 获取当前系统登录的用户名
            for kill_pid in appium_pid_list:
                automationframework.os.popen('kill %s' % kill_pid)  # 关闭appium服务
            automationframework.os.popen('kill %s' % appium_pid)  # 关闭Appium 主进程Pid

    # 读取用例操作类型
    def read_case_operate_type(self, file_name, run_sheel_name, appium_driver):
        pass_case_count = 0  # 执行用例的通过数
        not_run_case = 0  # 不执行的用例数
        run_case_nows, run_case_column, run_sheel = data_read.DataRead.read_case_file(file_name, run_sheel_name)
        print("正在读取测试用例,请稍后...")
        event_id = automationframework.time.strftime('%Y%m%d%H%M%S', automationframework.time.localtime())  # 每台设备运行的eventid
        print("执行用例的事件ID为: %s " % (event_id))
        run_case_now_count = 1  # 遍历用例表格计数器 从1 开始 第一行不算
        case_report_list = []  # 存放测试结果列表,然后去保存到数据库
        end_case_number = []  # Excel end操作类型标记列表
        if_case_number = []  # Excel if 操作类型标记列表
        if_number = 0  # 用例中 if计数器

        for if_end_count in range(1, run_case_nows):  # if_end_count if和end 计数器
            operate_types = run_sheel.row_values(if_end_count)[1]  # 获取Excel所有操作类型
            if 'if' in operate_types:
                if_case_number.append(if_end_count)  # 获取操作类型为if 在Excel中的序号
            if 'end' in operate_types:
                end_case_number.append(if_end_count)  # 获取操作类型为end 在Excel中的序号

        while run_case_now_count < run_case_nows:
            try:
                case_id = int(run_sheel.row_values(run_case_now_count)[0])  # 用例编号
            except Exception as error_result:
                print('代码执行错误,错误内容为: |', error_result, '| 遇到错误的方法名: read_case_operate_type() -> case_id')
                case_id = 0000
            operate_type = run_sheel.row_values(run_case_now_count)[1]  # 操作类型
            element_attribute = run_sheel.row_values(run_case_now_count)[2]  # 元素属性
            parameter = run_sheel.row_values(run_case_now_count)[3]  # 参数
            try:
                if (int(parameter) == parameter):
                    parameter = str(int(parameter))
            except:
                pass
            case_describe = run_sheel.row_values(run_case_now_count)[5]  # 步骤描述
            case_execute = run_sheel.row_values(run_case_now_count)[6]  # 用例执行状态
            stat_case_time = automationframework.time.time()  # 开始执行用例时间
            if 'Y' in case_execute or 'y' in case_execute:
                if operate_type == '等待时间':
                    try:
                        automationframework.time.sleep(int(parameter))  # 先读取用例中的time，进行转化若无法转化则取默认值3
                    except:
                        automationframework.time.sleep(self.wait_sleep_time)
                    case_report = '用例编号:%s,执行通过。' % case_id
                    print(case_report)
                elif '点击_' in operate_type:
                    case_report = automation_operate_function.AutomationOperate.app_operate_click(operate_type, element_attribute, appium_driver,
                                                                                                  case_id)
                    print(case_report)
                elif '滑动' in operate_type:
                    case_report = automation_operate_function.AutomationOperate.app_operate_slide(operate_type, appium_driver, case_id, self.wait_sleep_time)
                    print(case_report)
                elif '长按_' in operate_type:
                    case_report = automation_operate_function.AutomationOperate.app_operate_long_click(operate_type, element_attribute, appium_driver,
                                                                                                       case_id)
                    print(case_report)
                elif '输入_' in operate_type:
                    case_report = automation_operate_function.AutomationOperate.app_operate_input(operate_type, element_attribute, appium_driver,
                                                                                                  case_id, parameter)
                    print(case_report)
                elif '物理按钮' in operate_type:
                    case_report = automation_operate_function.AutomationOperate.app_operate_physics_key(appium_driver, case_id, int(parameter))
                    print(case_report)
                elif '查找_' in operate_type:
                    case_report = automation_operate_function.AutomationOperate.app_operate_check_element(operate_type, element_attribute,
                                                                                                          appium_driver, case_id, self.wait_element_time)
                    print(case_report)
                elif '切换' == operate_type:
                    case_report = automation_operate_function.AutomationOperate.app_change_system_webview(appium_driver, case_id, parameter, self.webview_wait_time)
                    print(case_report)

                elif '快速' in operate_type:
                    case_report = automation_operate_function.AutomationOperate.app_fast_change_system_webview(appium_driver, case_id, parameter, self.webview_wait_time)
                    print(case_report)

                elif 'if' in operate_type:
                    case_report = automation_operate_function.AutomationOperate.app_operate_check_element(operate_type, element_attribute,
                                                                                                          appium_driver, case_id, self.wait_element_time)
                    if "执行通过" not in case_report:
                        print(case_report)
                        # try:
                        #     x = end_case_number[if_number]
                        # except IndexError:
                        #     if len(end_case_number) - 1 >= 0:
                        #         x = end_case_number[len(end_case_number) - 1]
                        #         print("当前用例中的if和and不等，请检查用例")
                        #     else:
                        #         print("当前用例中的if和and不等，请检查用例")
                        #         pass
                        if len(end_case_number) == len(if_case_number):
                            run_case_now_count = end_case_number[if_number]
                        else:
                            print("当前用例中的if和and不等，请检查用例")
                            run_case_now_count = end_case_number[-1]
                    if_number += 1
            else:
                not_run_case += 1
                case_report = '用例编号:%s,执行状态为No,故不执行。' % (case_id)
                print(case_report)
            if '执行通过' in case_report:
                pass_case_count += 1  # 当用例执行通过，则加1
            end_case_time = automationframework.time.time()  # 结束用例时间
            case_report_dictionary = {
                'devicesexecute': 'Yes',
                'operatetype': operate_type,
                'element': element_attribute,
                'parameter': parameter,
                'rundescribe': case_describe,
                'caseexecute': case_execute,
                'runcasetime': round(end_case_time - stat_case_time, 2),
                'caseid': case_id,
                'eventid': event_id,
                'casereport': case_report,
                'createdtime': automationframework.time.strftime("%Y-%m-%d %H:%M:%S", automationframework.time.localtime()),
                'updatetime': automationframework.time.strftime("%Y-%m-%d %H:%M:%S", automationframework.time.localtime())
            }
            case_report_list.append(case_report_dictionary)  # 把数据存到列表中
            run_case_now_count += 1  # 循环计数器 +1
        return run_case_nows - 1, pass_case_count, not_run_case, case_report_list  # 返回用例总数、执行通过用例的数量、执行用例结果

    # 执行app自动化用例
    def run_app_automation_case(self, file_name, configure_sheel_name, run_sheel_name, device_id, appium_port):
        # filename 用例名称 configure_sheel_name 配置表格 run_sheel_name 执行用例表格 device_id 设备id
        case_amount, pass_case_count, not_run_case = 0, 0, 0  # 初始化case_amount, pass_case_count, not_run_case 如果没有获取到则返回0
        is_execute_configure = ''  # 默认空字符串
        configure_case_rows, configure_case_column, configure_sheel = data_read.DataRead.read_case_file(file_name,
                                                                                                        configure_sheel_name)
        for i in range(1, configure_case_rows):
            is_execute_configure = configure_sheel.row_values(i)[4]  # 获取当前配置是否执行
            if len(is_execute_configure) > 0 and '是' in is_execute_configure:
                app_package = configure_sheel.row_values(i)[0]  # 获取app 包名
                app_activity = configure_sheel.row_values(i)[1]  # 获取启动的activity
                app_path = configure_sheel.row_values(i)[2]  # 获取apk的路径
                check_is_clear_data = configure_sheel.row_values(i)[3]  # 检查是否清除app数据
                execute_uninstall_app = configure_sheel.row_values(i)[5]  # 检查是否需要删除apk
                break  # 只要获取到一个就执行该配置
        try:
            platform_version = self.get_device_android_version(device_id)  # 获取当前设备的Android系统版本
        except    Exception as error_result:
            print('代码执行错误,错误内容为: |', error_result, '| 遇到错误的方法名: get_device_android_version()')
            platform_version = '4.4.2'

        if len(is_execute_configure) > 0 and '是' in is_execute_configure:  # 是否要执行用例
            if self.check_device_packages(device_id, app_package) or automationframework.os.path.exists(
                    app_path):  # automationframework.os.path.exists(app_path) 检查当前路径是否有此文件 返回true和false
                if len(check_is_clear_data) > 0 and '是' in check_is_clear_data:  # 检查是否需要清除设备app信息,如果是则清除
                    if self.check_device_packages(device_id, app_package):
                        if RunAppAutomation().clear_app_data(device_id, app_package):
                            print('清除设备: %s app 数据成功.' % (device_id))
                        else:
                            print('清除设备: %s app 数据失败。未在此设备中找到包名: %s' % (device_id, app_package))
                            automationframework.time.sleep(self.wait_sleep_time)  # 在清除APP数据后，等待3秒再连接appium,防止出现问题
                    else:
                        print('当前设备未安装apk,不需要清除app数据,未执行app数据清除操作.')
                try:
                    get_webview_path = RunAppAutomation().get_webview_path(device_id)  # 返回返回True则配置webview_path
                    if get_webview_path:
                        webview_path = get_webview_path
                    else:
                        webview_path = ''
                except Exception as error_result:
                    print('代码执行错误,错误内容为: |', error_result, '| 遇到错误的方法名: get_webview_path()')
                    webview_path = ''
                connect_appium_device_config = RunAppAutomation().original_device_info(device_id, 'Android',
                                                                                       platform_version,
                                                                                       app_package, app_activity,
                                                                                       app_path, webview_path)  # 初始化appium 连接设备信息

                try:
                    driver = webdriver.Remote('http://localhost:%s/wd/hub' % appium_port,
                                              connect_appium_device_config)  # 连接appium
                    driver.implicitly_wait(30)  # 在未获取到元素时 等待 30 秒
                    case_amount, pass_case_count, not_run_case, case_report_list = RunAppAutomation().read_case_operate_type(
                        file_name,
                        run_sheel_name,
                        driver)  # 读取用例操作类型 并执行
                    # 获取总用例数、执行用过的用例数、用例执行结果的列表
                    try:
                        mysql_cursor, connect_mysql = data_read.DataRead.save_database()  # 获取数据库游标 游标执行sql,以及连接的变量用于关闭数据连接
                        if len(case_report_list) > 0:
                            add_device_info_count = 0  # case report 加入设备信息计数器
                            while add_device_info_count < len(case_report_list):
                                case_report_list[add_device_info_count].update(
                                    {'devicesinfos': "设备名：" + str(device_id) + "," + "系统版本信息：" + 'Android' + str(
                                        platform_version)}),
                                case_report_list[add_device_info_count].update({'appiumport': appium_port}),
                                case_report_list[add_device_info_count].update({'devicesexecute': 'Yes'})
                                add_device_info_count += 1
                            execute_sql_count = 0  # 执行sql数据计数器
                            while execute_sql_count < len(case_report_list):
                                devicesinfos = str(case_report_list[execute_sql_count].get('devicesinfos'))
                                appiumport = str(case_report_list[execute_sql_count].get('appiumport'))
                                devicesexecute = str(case_report_list[execute_sql_count].get('devicesexecute'))
                                operatetype = str(case_report_list[execute_sql_count].get('operatetype'))
                                element = str(case_report_list[execute_sql_count].get('element'))
                                parameter = str(case_report_list[execute_sql_count].get('parameter'))
                                rundescribe = str(case_report_list[execute_sql_count].get('rundescribe'))
                                caseexecute = str(case_report_list[execute_sql_count].get('caseexecute'))
                                runcasetime = str(case_report_list[execute_sql_count].get('runcasetime'))
                                caseid = str(case_report_list[execute_sql_count].get('caseid'))
                                eventid = str(case_report_list[execute_sql_count].get('eventid'))
                                casereport = str(case_report_list[execute_sql_count].get('casereport'))
                                createdtime = str(case_report_list[execute_sql_count].get('createdtime'))
                                updatetime = str(case_report_list[execute_sql_count].get('updatetime'))
                                if '"' in element:
                                    element = automationframework.pymysql.escape_string(element)
                                execute_sql = "insert into `automationquery_automation_function_app`  (`devicesinfos`,`appiumport`,`devicesexecute`,`operatetype`," \
                                              "`element`,`parameter`,`rundescribe`,`caseexecute`,`runcasetime`,`caseid`,`eventid`,`casereport`,`createdtime`," \
                                              "`updatetime`)VALUES('%s','%s','%s','%s',\"%s\",'%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (
                                                  devicesinfos,
                                                  appiumport,
                                                  devicesexecute,
                                                  operatetype,
                                                  element,
                                                  parameter,
                                                  rundescribe,
                                                  caseexecute,
                                                  runcasetime,
                                                  caseid,
                                                  eventid,
                                                  casereport,
                                                  createdtime,
                                                  updatetime,
                                              )
                                mysql_cursor.execute(execute_sql)
                                execute_sql_count += 1
                            connect_mysql.commit()  # 提交数据
                            connect_mysql.close()  # 关闭数据库连接
                        else:
                            pass
                    except Exception as error_result:
                        print('代码执行错误,错误内容为: |', error_result, '| 遇到错误的方法名: run_app_automation_case() -> MySQL保存数据错误')
                        print("保存数据失败。")
                except Exception as error_result:
                    print('代码执行错误,错误内容为: |', error_result, '| 遇到错误的方法名: run_app_automation_case() -> webdriver.Remote')
                    print('连接Appium失败,连接设备号为: %s 端口号为: %s ' % (device_id, appium_port))
                driver.quit()  # 退出appium
                if '是' in execute_uninstall_app:
                    if RunAppAutomation().uninstall_app_data(device_id, app_package):
                        print('删除设备: %s app 成功.' % (device_id))
                    else:
                        print('删除设备: %s app 失败。' % (device_id))
            else:
                print('apk 路径错误或执行的设备未安装匹配包名的apk,包名: %s, 设备名: %s' % (app_package, device_id))
        else:
            print('app 配置信息未获取到,请检查Excel appdeviceinfo中\'是否启用\'项。')
        return case_amount, pass_case_count, not_run_case, eventid  # 返回总用例数、执行用过的用例数、事件id 用于发送邮件的统计

    # 设备连接Appium 配置文件
    def original_device_info(self, udid, platform_name, platform_version, app_package, app_activity, app_path, webview_path):
        device_info = {
            'deviceName': udid,
            'platformName': platform_name,
            'platformVersion': platform_version,
            'appPackage': app_package,
            'appActivity': app_activity,
            'udid': udid,
            'unicodeKeyboard': True,
            'resetKeyboard': True,
        }
        if webview_path != '':
            device_info['chromedriverExecutableDir'] = webview_path
        if app_path != '' and automationframework.os.path.exists(app_path):  # automationframework.os.path.exists(app_path) 检测文件是否存在 存在返回true
            device_info['app'] = app_path
        else:
            print('Excel 中 appdeviceinfo apk路径无法找到对应的apk,正在使用设备中的apk。')

        if platform_version > '7.0':
            print('当前Android系统版本为: %s,' % (platform_version), '正在使用 uiautomator2')
            device_info['automationName'] = 'uiautomator2'
            device_info['noSign'] = True
        return device_info


if __name__ == "__main__":
    pass
